# Filename: jit-mda-install-failover.sh
# Usage: jit-mda-install-failover <image name> <primaryIP> <backupIP> <backupPort> <interval>
# Example: jit-mda-install-failover vm01 10.0.0.1 10.0.0.2 8002 200
#
# Creates a VM instance and starts failover protection on it,
# provided the DRBD resource is available on the Backup host.


imagename=$1
primaryip=$2
backupip=$3
backupport=$4
interval=$5

VMCONFIG=/etc/xen/${imagename}.cfg
REMUSLOG=/root/remus.log
REMUSERR=/root/remus.err
SCRIPTS_FOLDER=/root/scripts
drbdAvailable="0"

echo `date +%H:%M:%S` Starting Script $0 $*
if [ -z "$imagename" -o -z "$primaryip" -o -z "$backupip" -o -z "$backupport" -o -z "$interval" ]; then
	echo Incorrect parameters
	echo "Usage: $0 <image name> <primaryIP> <backupIP> <backupPort> <interval>"
else
	rm -f $REMUSLOG $REMUSERR
	touch $REMUSLOG $REMUSERR

	# Checking for DRBD status, vital for further steps.
	$SCRIPTS_FOLDER/jit-mda-check-drbd.sh $imagename $backupip >> $REMUSLOG
	drbdAvailable=`echo $?`
	if [ "$drbdAvailable" == "0" ]; then
		# Synchronizing DRBD volumes for the first time and allowing some time
		drbdadm -- --overwrite-data-of-peer primary $imagename
		sleep 60

		# Instantiating VM and protecting
		xm create $VMCONFIG 2>>$REMUSERR
		nohup remus -i $interval $imagename $backupip -p $backupport >>$REMUSLOG 2>>$REMUSERR &

		echo Remus protection activated, backup on $backupip:$backupport
		echo For more information, read $REMUSLOG and $REMUSERR
	else
		echo ERROR: Unable to create VM. DRBD resource $imagename unavailable on server $backupip
	fi
fi
echo `date +%H:%M:%S` Finishing Script $0
exit 0
